package jcu.mobile.library.namespace;


import java.util.ArrayList;
import java.util.List;

import com.parse.Parse;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class NewArrivalActivity extends Activity{

	
	ArrayList<BookRecord> bookList;
	BookRecord bookUpdater;
	bookListAdapter bookAdapter;
	int position;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		Parse.initialize(this, "1GlGZQ1XWU34mHgFyDHZiZRr6HTTSWOZo2nSAowy", "GKVclKTd6TIPxLVPPbDiyvzAMoWA2XLf4ZdZYFwI");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insert_newbook);
        
        
        bookList = new ArrayList<BookRecord>();

        
        //parse query to find latest book update
        ParseQuery query = new ParseQuery("Book");
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback() {
            public void done(List<ParseObject> queryResult, ParseException e) {
                if (e == null) {
                    for(int i=0; i<queryResult.size(); i++)
                    {
                    	
                    	
                    	//code to display the book list when its status is available
                    	if (queryResult.get(i).getBoolean("Available_Status") == true)
                    	{
	                    	bookUpdater = new BookRecord(queryResult.get(i).getString("Title"), "Currently Available");
	                    	bookList.add(bookUpdater);
	                    	Log.d("score", "scorelist = "+ queryResult.size());
                    	}
                    	
                    	
                    	//code to display the book list when its status is unavailable
                    	else
                    	{
                    		
                    		//date format (1 to display as '1st', 2 as '2nd', 3 as '3rd', etc...)
                    		String date = null;
                    		if (queryResult.get(i).getDate("Available_Date").getDate() == 1 || queryResult.get(i).getDate("Available_Date").getDate() == 31)
                    		{
                    			date = "st";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getDate() == 2 || queryResult.get(i).getDate("Available_Date").getDate() == 22)
                    		{
                    			date = "nd";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getDate() == 3 || queryResult.get(i).getDate("Available_Date").getDate() == 23)
                    		{
                    			date = "rd";
                    		}
                    		else
                    		{
                    			date = "th";
                    		}
                    		
                    		
                    		
                    		//month to display in full name (January, february, etc.)
                    		String month = null;
                    		if (queryResult.get(i).getDate("Available_Date").getMonth() == 1)
                    		{
                    			month = "January";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 2)
                    		{
                        		month = "February";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 3)
                    		{
                        		month = "March";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 4)
                    		{
                        		month = "April";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 5)
                    		{
                        		month = "May";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 6)
                    		{
                        		month = "June";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 7)
                    		{
                        		month = "July";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 8)
                    		{
                        		month = "August";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 9)
                    		{
                        		month = "September";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 10)
                    		{
                        		month = "October";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 11)
                    		{
                        		month = "November";
                    		}
                    		else if (queryResult.get(i).getDate("Available_Date").getMonth() == 12)
                    		{
                        		month = "Decemeber";
                    		}

                    			//prepare each record and pass it to the arraylist
    	                    	bookUpdater = new BookRecord(queryResult.get(i).getString("Title"), "Will Be Available On "+queryResult.get(i).getDate("Available_Date").getDate()+date+" , "+ month);
    	                    	bookList.add(bookUpdater);
    	                    	
    	                    	//event log to check the query result
    	                    	Log.d("book", "book result = "+ queryResult.size());               		
                    	}
                    }
                }
                ListView listView = (ListView) findViewById(R.id.ListViewId);
                listView.setAdapter(bookAdapter);
                
                //display detailed information of clicked items on listview using itemclicklistener
                listView.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView arg0, View view, int arg2,long itemID) {

                        position = arg2;
                        setContentView(R.layout.book_detail);
                        ParseQuery query = new ParseQuery("Book");
                        query.findInBackground(new FindCallback() {
                            public void done(List<ParseObject> queryResult, ParseException e) 
                            {
                                if (e == null)
                                {
                                    TextView tv = (TextView) findViewById(R.id.bookdetail);
                                    Button request = (Button) findViewById(R.id.request);
                                    ImageView iv = (ImageView) findViewById(R.id.imageView1);
                                    
                                    
                                    //code to function when the book status is available
                                    if (queryResult.get(position).getBoolean("Available_Status") == true)
                                    {
                                    	String s = "Status - Currently Available";
                                    	tv.setText(Html.fromHtml("<big><b>"+queryResult.get(position).getString("Title")+"</b></big><br><br>Author - "+queryResult.get(position).getString("Author")+"<br><br>Year - "+queryResult.get(position).getInt("Publish_Year")+"<br><br>"+s));
                                    	iv.setVisibility(1);
                                    	request.setVisibility(1);
                                    	request.setClickable(true);		//'Request' button to be clickable for the book is available
                                    	
                                    	//action on book request
                                    	request.setOnClickListener(new OnClickListener() {
                                        	
                                        	public void onClick(View v) {  
                                        		Context context = getApplicationContext();
                                        		CharSequence text = "You've successfully reserved the item and will be notified as soon as the book is available.";
                                        		int duration = Toast.LENGTH_LONG;

                                        		
                                        		//toast message to display when the item is clicked
                                        		Toast toast = Toast.makeText(context, text, duration);
                                        		toast.show();
                                        	}
                                        });
                                    }
                                    else
                                    {
                                    	String s = "Status - Currently Unavailable";
                                    	tv.setText(Html.fromHtml("<big><b>"+queryResult.get(position).getString("Title")+"</b></big><br><br>Author - "+queryResult.get(position).getString("Author")+"<br><br>Year - "+queryResult.get(position).getInt("Publish_Year")+"<br><br>"+s));
                                    	iv.setVisibility(1);
                                    	request.setVisibility(1);
                                    	request.setEnabled(false);	//"Request" button to disable for the book is occupied
                                    }
                                }
                                else 
                                {
                                	
                                }

                            }
                        });
                    }
                });

            }
        });
        bookAdapter = new bookListAdapter(this, android.R.layout.simple_list_item_1, bookList);


    }
	

	
	public class bookListAdapter extends ArrayAdapter<BookRecord> {
		private ArrayList<BookRecord> bookList;

		public bookListAdapter(Context context, int textViewResourceId, ArrayList<BookRecord> bookList) {
			super(context, textViewResourceId, bookList);
			this.bookList = bookList;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_newbook, null);
			}
			
			BookRecord user = bookList.get(position);
			if (user != null) {
				TextView title = (TextView) v.findViewById(R.id.title);
				TextView author = (TextView) v.findViewById(R.id.author);
				ImageView iv = (ImageView) v.findViewById(R.id.avatar);

				/*ParseObject query = new ParseObject("Book");
				ParseFile p = (ParseFile) query.get("Image");
				p.getDataInBackground(new GetDataCallback() {
					public void done(byte[] data, ParseException e)
					{
						if (e==null)
						{
							ImageView iv = (ImageView) findViewById(R.id.avatar);
							iv.setImageResource(data[0]);
						}
						else
						{
							ImageView iv = (ImageView) findViewById(R.id.avatar);
							iv.setImageResource(data[0]);
						}
					}
				});*/
				if (title != null) {
					title.setText(user.title);
				}

				if(author != null) {
					author.setText(user.author );
				}
				
				
			}
			return v;
		}
	}
	
	public class BookRecord {
		public String title;
		public String author;
		
		public BookRecord(String title, String author) {
			this.title = title;
			this.author = author;
		}
	}
}
